import { defineStore } from 'pinia'
import axios from 'axios'
import Cookies from 'js-cookie'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        token: Cookies.get('token') || null,
        isAuthenticated: !!Cookies.get('token'),
        loading: false,
        error: null
    }),

    actions: {
        // 登录 - 修改请求格式
        async login(username, password) {
            this.loading = true
            this.error = null
            try {
                // 创建表单数据
                const formData = new FormData()
                formData.append('username', username)
                formData.append('password', password)

                const response = await axios.post(
                    `${API_BASE_URL}/api/auth/login`,
                    formData,  // 使用FormData而非JSON
                    {
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        }
                    }
                )

                const { token, user } = response.data
                this.token = token
                this.user = user
                this.isAuthenticated = true

                // 存储token到cookie，有效期7天
                Cookies.set('token', token, { expires: 7 })

                // 设置axios默认headers
                axios.defaults.headers.common['Authorization'] = `Bearer ${token}`

                return true
            } catch (error) {
                this.error = error.response?.data?.detail || '登录失败，请检查用户名和密码'
                return false
            } finally {
                this.loading = false
            }
        },

        // 其他代码保持不变...
        async logout() {
            // ...
        },

        async validateToken() {
            // ...
        }
    }
})
